<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>适配设备像素比</title>
</head>
<style>
    body {
        margin: 0;
        overflow: hidden;
    }

    #canvas1 {
        background-color: antiquewhite;
    }

    #canvas2 {
        background-color: aquamarine;
    }
</style>

<body>
    <canvas id="canvas1"></canvas>
    <canvas id="canvas2"></canvas>
    <script>
        // 视口宽高
        const [width, height] = [220, 400]

        // 不做分辨适配
        const canvas1 = document.getElementById('canvas1')
        const ctx1 = canvas1.getContext("2d")
        canvas1.width = width
        canvas1.height = height
        // 绘图
        ctx1.font = "60px Arial"
        ctx1.fillText("canvas", 10, 100)

        // 设备像素比
        const canvas2 = document.getElementById('canvas2')
        const ctx2 = canvas2.getContext("2d")
        //  通过window对象获取设备像素比devicePixelRatio
        // 视口宽高 * 设备像素比
        const devicePixelRatio = window.devicePixelRatio || 1
        console.log(devicePixelRatio); // 放大125 1.25
        // 让canvas的画布尺寸乘以设备像素比，将canvas·画布尺寸放大
        canvas2.width = width *devicePixelRatio
        canvas2.height = height *devicePixelRatio
        // 文字同步变大
        ctx2.scale(devicePixelRatio, devicePixelRatio)

        // 设置canvas css尺寸，定义画布的视觉大小 等于原始的视觉宽高
        canvas2.style.width = width + "px"
        canvas2.style.height = height + "px"
        
        // 绘图
        ctx2.font = "60px Arial"
        ctx2.fillText("canvas", 10 , 100 )

    </script>

</body>

</html>